/*
 * Copyright 2012-2014 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.jqd.framework.core.hessian.biz.action.support;

import java.lang.reflect.Method;

import org.springframework.context.ApplicationContext;

import com.jqd.framework.core.hessian.biz.action.ActionHandlerAdapter;
import com.jqd.framework.core.hessian.model.ServiceRequest;
import com.jqd.framework.core.hessian.model.ServiceResponse;
import com.jqd.framework.core.spring.context.ApplicationContextFactory;
import com.jqd.framework.util.Assert;

/**
 * 
 * TODO
 * 
 * @author liaozhicheng.cn@gmail.com
 * @date 2012-6-11
 * @since 1.0
 */
public class BeanMethodNameActionHandlerAdapter implements ActionHandlerAdapter {
	
	@Override
	public boolean supports(ServiceRequest serviceRequest, Object actionHandler) {
		
		String actionId = serviceRequest.getRequestedActionID();
		Assert.hasText(actionId,
				"ServiceRequest property 'REQUESTED_ACTION_ID' can not be null or empty");
		
		ApplicationContext ctx = ApplicationContextFactory.getApplicationContext();
		String[] beanNames = ctx.getBeanNamesForType(actionHandler.getClass());
		for (String beanName : beanNames) {
			if (actionId.startsWith(beanName)) {
				
				return true;
			}
		}
		return false;
	}
	
	
	@Override
	public ServiceResponse handle(ServiceRequest serviceRequest, Object actionHandler) {
		Assert.notNull(actionHandler, "Parameter 'actionHandler' can not be null");
		
		String actionId = serviceRequest.getRequestedActionID();
		String methodName = BeanMethodNameActionIdUtils.getMethodName(actionId);
		
		ServiceResponse serviceResponse = null;
		
		Method method = null;
		try {
			method = actionHandler.getClass().getMethod(methodName, ServiceRequest.class);
			
			serviceResponse = (ServiceResponse) method.invoke(actionHandler, serviceRequest);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return serviceResponse;
	}
	
}
